﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Text.RegularExpressions;

namespace TCPCli
{
    class Program
    {
        static void Main (string [] args)
        {
            if (! argumentosOk (args))
            {
                uso();
                return;
            }

            for (; ; )
            {
                for (int i = 0; i < int.Parse(args[0]); ++i)
                    ThreadPool.QueueUserWorkItem(
                        new WaitCallback((o) => trabajar(args[1], int.Parse(args[2])))
                    );

                Thread.Sleep(int.Parse(args[3]));
            }
        }

        private static void uso ()
        {
            // 0 cantidad de clientes
            // 1 ip
            // 2 puerto
            // 3 milis duerme

            Console.WriteLine (
                "Uso: \r\n" +
                "\ttcpcli cantidadDeClientes ip puerto milisDuerme \r\n" +
                "\ttcpcli 50 127.0.0.1 5968 5000 \r\n"
            );
        }

        private static bool argumentosOk (string [] args)
        {
            return
               ((args.Length == 4)                  &&
                (Regex.IsMatch(args[0], "[0-9]+"))  &&
                (Regex.IsMatch(args[1], "[0-9]+.[0-9]+.[0-9]+.[0-9]+")) &&
                (Regex.IsMatch(args[2], "[0-9]+"))  &&
                (Regex.IsMatch(args[2], "[0-9]+")));
        }

        static void trabajar (string ipServer, int puertoServer)
        {
            try
            {
                TcpClient tcpClient = new TcpClient();
                tcpClient.Connect (ipServer, puertoServer);

                NetworkStream ns = tcpClient.GetStream();

                int start = Environment.TickCount;
                byte[] datos = Encoding.ASCII.GetBytes("imei:359587010124900,tracker,0809231929,13554900601,F,112909.397,A,2234.4669,N,11354.3287,E,0.11,;");

                ns.Write (datos, 0, datos.Length);
                ns.Flush ();
                int end = Environment.TickCount;

                Console.WriteLine("120 bytes {0} milis", end - start);

                tcpClient.Close  ();
            }
            catch (Exception e)
            {
                Console.Error.WriteLine (e.Message);
            }
        }
    }
}
